﻿//11. Write a method that adds two polynomials. Represent them as arrays of their coefficients as in the example below:
//		x2 + 5 = 1x2 + 0x + 5  


using System;
using System.Collections.Generic;
using System.Text;

class AddsTwoPolynomials
{
    static void Main()
    {
        int[] firstPolynom = { 3, -5, 6, 0, 7, 2, -2 };
        int[] secondPolynom = { 0, 2, 3, -9, -8, 1 };
        Console.WriteLine("First polynomial: ".PadLeft(24, '-') + PolynomToString(firstPolynom));
        Console.WriteLine("Second polynomial: ".PadLeft(24, '-') + PolynomToString(secondPolynom));
        int[] sum = AddPolynomials(firstPolynom, secondPolynom);
        Console.WriteLine("\n" + "Sum: ".PadLeft(24, '-') + PolynomToString(sum));
    }
    static int[] AddPolynomials(int[] firstPolynom, int[] secondPolynom)
    {
        int[] sum = new int[Math.Max(firstPolynom.Length, secondPolynom.Length)];
        for (int i = 0; i < firstPolynom.Length; i++)
        {
            sum[i] = firstPolynom[i];
        }
        for (int i = 0; i < secondPolynom.Length; i++)
        {
            sum[i] = sum[i] + secondPolynom[i];
        }
        return sum;
    }
    static string PolynomToString(int[] polynomial)
    {
        StringBuilder result = new StringBuilder();

        for (int i = polynomial.Length - 1; i >= 0; i--)
        {
            if (polynomial[i] != 0)
            {
                result.Append(polynomial[i] > 0 ? "+": "-");
                result.Append(Math.Abs(polynomial[i]));
                if (i != 0)
                {
                    result.Append(i > 1 ? "x^" + i : "x");
                }
            }
        }
        return result.ToString();
    }
}
